<?php

class ecI18n{

  public static function preferedLanguage($params = array(),$httpAcceptLanguage="auto")
  {
    if(!$availableLanguages = self::getAvaibleLanguage($params))
    {
      $availableLanguages = array('en-US');
    }
    
    if($httpAcceptLanguage == "auto")
      $httpAcceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

    // standard  for HTTP_ACCEPT_LANGUAGE is defined under
    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
    // pattern to find is therefore something like this:
    //    1#( language-range [ ";" "q" "=" qvalue ] )
    // where:
    //    language-range  = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
    //    qvalue         = ( "0" [ "." 0*3DIGIT ] )
    //            | ( "1" [ "." 0*3("0") ] )
    preg_match_all("/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?" .
                   "(\s*;\s*q\s*=\s*(1\.0{0,3}|0\.\d{0,3}))?\s*(,|$)/i",
                       $httpAcceptLanguage, $hits, PREG_SET_ORDER);

    // default language (in case of no hits) is the first in the array
    $bestLang = $availableLanguages[0];
    $bestQval = 0;
    $languagePrefix = "";

    foreach ($hits as $arr)
    {
      // read data from the array of this hit
      $languagePrefix = strtolower ($arr[1]);
      if (!empty($arr[3]))
      {
        $langRange = strtolower ($arr[3]);
        $language = $languagePrefix . "-" . $langRange;
      }
      else
      {
        $language = $languagePrefix;
      }

      $qValue = 1.0;
      if (!empty($arr[5]))
        $qValue = floatval($arr[5]);

      // find q-maximal language
      if (in_array($language,$availableLanguages) && ($qValue > $bestQval))
      {
        $bestLang = $language;
        $bestQval = $qValue;
      }

      // if no direct hit, try the prefix only but decrease q-value by 10% (as http_negotiate_language does)
      else if (in_array($languagePrefix,$availableLanguages) && (($qValue*0.9) > $bestQval))
      {
        $bestLang = $languagePrefix;
        $bestQval = $qValue*0.9;
      }
    }
    return $bestLang;
  }

  public static function getAvaibleLanguage($params)
  {
    if(array_key_exists('lang', $params))
      if(is_array($params['lang']))
        return $params['lang'];
      else
        return false;
    else
      return false;
  }
}

?>
